package com.hmx.openplatform.gateway.filters;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmx.openplatform.commons.constans.BaseResultBean;
import com.hmx.openplatform.commons.constans.ExceptionDict;
import com.hmx.openplatform.commons.constans.SystemParams;
import com.hmx.openplatform.gateway.feign.CacheService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * Description:
 *
 * @author hmx
 * @date Created on 2021/5/23
 */
@Component
public class SystemParamsFilter extends ZuulFilter {
    @Autowired
    private CacheService cacheService;

    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 我们应该先判断用户有没有传递参数，没有的话就返回错误数据
     * @return
     */
    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        //我们要做的事情是判断有没有传递我们要求的参数
        //需要的数据内容: 1 我们要求传递的参数是什么
        //我们如何知道我们要求传递的参数
        HttpServletRequest request = context.getRequest();
        try {
            //我们保存在了redis中，所以从redis中查询即可
            Set<Object> systemparamsSet = cacheService.sMembers(SystemParams.SYSTEMPARAMS);
            //当我们有了数据之后，怎么知道用户有没有传递呢
            //只要遍历我们的参数，挨个获取一次数据，没有值的都是没有传递的
            if(systemparamsSet != null){
                for (Object param : systemparamsSet) {
                    String value = request.getParameter(param.toString());//获取当前参数的值
                    if(StringUtils.isEmpty(value)){
                        //代表当前参数没有传递
                        context.setSendZuulResponse(false);
                        HttpServletResponse response = context.getResponse();
                        response.setContentType("application/json;charset=utf-8");
                        BaseResultBean bean = new BaseResultBean();
                        bean.setCode(ExceptionDict.SYSTEMPARAM_MISSED);
                        bean.setMsg("必须传递参数名为: " + param + "的数据");

                        context.setResponseBody(objectMapper.writeValueAsString(bean));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }



        //如果有没有传递的参数，就返回错误数据给用户
        return null;
    }
}
